{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TensorRT Runtime\n",
    "\n",
    "This example walks through the basic usecase of:\n",
    "  1. initialization the infer-runtime\n",
    "  2. loading a model\n",
    "  3. allocating resources\n",
    "  4. inspecting the input/output bindings of the model\n",
    "  5. evaluating the model using async futures\n",
    "  6. testing for correctness"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import time\n",
    "import numpy as np\n",
    "import wurlitzer\n",
    "\n",
    "import trtlab\n",
    "import infer_test_utils as utils\n",
    "\n",
    "# this allows us to capture stdout and stderr from the backend c++ infer-runtime\n",
    "display_output = wurlitzer.sys_pipes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!trtexec --onnx=/work/models/onnx/mnist-v1.3/model.onnx --saveEngine=/work/models/onnx/mnist-v1.3/mnist-v1.3.engine"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Initialize infer-runtime\n",
    "\n",
    "The most important option when initializing the infer-runtime is to set the maximum number of conncurrent executions that can be executed at any given time.  This value is tunable for your application.  Lower setting reduce latency; higher-settings increase throughput.  Evaluate how your model performs using ...TODO-this-notebook..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with display_output():\n",
    "    models = infer.InferenceManager(max_executions=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Register a Model\n",
    "\n",
    "To register a model, simply associate a `model_name` with a path to a TensorRT engine file. The returned object is an `InferRunner` object.  Use an `InferRunner` to submit work to the backend inference queue."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with display_output():\n",
    "    mnist = models.register_tensorrt_engine(\"mnist\", \"/work/models/onnx/mnist-v1.3/mnist-v1.3.engine\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Allocate Resources\n",
    "\n",
    "Before you can submit inference requests, you need to allocate some internal resources.  This should be done anytime new models are registered.  There maybe a runtime performance interruption if you update the resources while the queue is full."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with display_output():\n",
    "    models.update_resources()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Inspect Model\n",
    "\n",
    "Query the `InferenceRunner` to see what it expects for inputs and what it will return for outputs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mnist.input_bindings()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mnist.output_bindings()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Submit Infer Requests\n",
    "\n",
    "`InferenceRunner.infer` accecpts a dict of numpy arrays that match the input description, submits this inference request to the backend compute engine and returns a future to a dict of numpy arrays.  \n",
    "\n",
    "That means, this method should returns almost immediately; however, that does not mean the inference is complete.  Use `get()` to wait for the result.  This is a blocking call."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = mnist.infer(Input3=np.random.random_sample([1,28,28]))\n",
    "result # result is a future"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = result.get()\n",
    "result # result is the value of the future - dict of np arrays"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with display_output():\n",
    "    start = time.process_time()\n",
    "    result = mnist.infer(**{k: np.random.random_sample(v['shape']) for k,v in mnist.input_bindings().items()})\n",
    "    print(\"Queue Time: {}\".format(time.process_time() - start))\n",
    "    result = result.get()\n",
    "    print(\"Compute Time: {}\".format(time.process_time() - start))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Test for Correctness\n",
    "\n",
    "Load test image and results.  [Thanks to the ONNX Model Zoo](https://github.com/onnx/models/tree/master/mnist) for this example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "inputs = utils.load_inputs(\"/work/models/onnx/mnist-v1.3/test_data_set_0\")\n",
    "expected = utils.load_outputs(\"/work/models/onnx/mnist-v1.3/test_data_set_0\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "utils.mnist_image(inputs[0]).show()\n",
    "expected[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "Submit the images to the inference queue, then wait for each result to be returned."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "results = [mnist.infer(Input3=input) for input in inputs]\n",
    "results = [r.get() for r in results]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Check results.\n",
    "TODO - update the utils to return dictionaries instead of arrays"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for r, e in zip(results, expected):\n",
    "    for key, val in r.items():\n",
    "        r = val.reshape((1,10))\n",
    "        np.testing.assert_almost_equal(r, e, decimal=3)\n",
    "        print(\"Test Passed\")\n",
    "        print(\"Output Binding Name: {}; shape: {}\".format(key, val.shape))\n",
    "        print(\"Result: {}\".format(np.argmax(utils.softmax(r))))\n",
    "        # r # show the raw tensor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
